package com.sike.netty.im.common.codc;

import cn.hutool.json.JSONUtil;
import com.sike.netty.im.common.command.CommandBody;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.enums.CommandTypeEnum;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;
import java.util.Optional;

/**
 * 指令 body 解码器
 *
 * @author chenssy
 * @date 2023/09/14
 */
public class CommandBodyDecoder extends MessageToMessageDecoder<Message> {
    @Override
    protected void decode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        // 获取指令
        CommandTypeEnum commandTypeEnum = CommandTypeEnum.getCommandType(msg.getHeader().getMessageType());
        Class typeClass = Optional.ofNullable(commandTypeEnum)
                .map(CommandTypeEnum::getCommandTypeClass)
                .orElseThrow(() ->new RuntimeException("该指令不存在"));

        CommandBody commandBody = (CommandBody) JSONUtil.toBean(JSONUtil.toJsonStr(msg.getBody()),typeClass);
        out.add(commandBody);
    }
}
